package com.cruise.h5.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cruise.common.mybatis.util.CommonBeanUtil;
import com.cruise.common.web.util.WebUtils;
import com.cruise.h5.mapper.VideoCommentLikeRecordMapper;
import com.cruise.h5.mapper.VideoCommentMapper;
import com.cruise.h5.mapper.VideoMapper;
import com.cruise.h5.pojo.dto.*;
import com.cruise.h5.pojo.entity.VideoComment;
import com.cruise.h5.pojo.entity.VideoCommentLikeRecord;
import com.cruise.h5.pojo.vo.CommentListVO;
import com.cruise.h5.pojo.vo.ReplyListOfCommentVO;
import com.cruise.h5.service.VideoCommentService;
import com.cruise.system.userapi.entity.SysUser;
import com.cruise.system.userapi.feignapi.FeignSystemApi;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cruise
 * @since 2021-03-25
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class VideoCommentServiceImpl extends ServiceImpl<VideoCommentMapper, VideoComment> implements VideoCommentService {


    @Resource
    private VideoCommentMapper videoCommentMapper;

    @Resource
    private VideoMapper videoMapper;

    @Resource
    private FeignSystemApi feignSystemApi;

    @Resource
    private VideoCommentLikeRecordMapper videoCommentLikeRecordMapper;

    @Override
    public void comment(VideoCommentDTO videoCommentDTO) {
        VideoComment videoComment = new VideoComment(WebUtils.getUserId(), WebUtils.getUserId());
        BeanUtils.copyProperties(videoCommentDTO, videoComment);
        videoCommentMapper.insert(videoComment);
        if(videoCommentDTO.getPid().equals(videoCommentDTO.getVideoId())){
            // 一级评论
            videoMapper.addCommentCount(videoCommentDTO.getVideoId());
        }else{
            // 二级评论
            videoCommentMapper.addCommentCount(videoCommentDTO.getPid());
        }

    }

    @Override
    public IPage<CommentListVO> commentList(CommentListDTO commentListDTO) {


        Page<VideoComment> videoPageParam = new Page<>(commentListDTO.getCurrent(), commentListDTO.getSize());
        Page<VideoComment> videoCommentPage =(Page<VideoComment>)videoCommentMapper.selectPage(videoPageParam , new QueryWrapper<VideoComment>().lambda().eq(VideoComment::getPid, commentListDTO.getVideoId()).orderByDesc(VideoComment::getLikeCount));
        IPage<CommentListVO> commentListVO = CommonBeanUtil.pageVo(videoCommentPage, CommentListVO.class);
        commentListVO.getRecords().forEach(item ->{

            // 补充用户信息
            SysUser createUser = feignSystemApi.findById(item.getCreateBy());
            item.setNickname(createUser.getNickname());
            item.setAvatar(createUser.getAvatar());

            // 补充是否 用户点击了 喜欢
            item.setIsAlreadyLike(isAlreadyLike(item.getId(),WebUtils.getUserId()));
            // 补充是否 用户点击了 踩
            item.setIsAlreadyDisLike(isAlreadyDisLike(item.getId(),WebUtils.getUserId()));

            // 加载 播放页的 每一条评论的回复列表
            int limit  = 3;
            int curr = 1;
            ArrayList<CommentListVO.ReplyItemLevel1> replyItemLevel1s = new ArrayList<>();
            Page<VideoComment> replyItmes = new Page<>(curr, limit);
            IPage<VideoComment> replyItmePage = videoCommentMapper.selectPage(replyItmes, new QueryWrapper<VideoComment>().lambda().eq(VideoComment::getPid, item.getId()).orderByDesc(VideoComment::getLikeCount));
            replyItmePage.getRecords().forEach(reply ->{
                SysUser user = feignSystemApi.findById(reply.getCreateBy());
                CommentListVO.ReplyItemLevel1 replyItemLevel1 = new CommentListVO.ReplyItemLevel1(user.getNickname(),reply.getContent());
                replyItemLevel1s.add(replyItemLevel1);
            });
            item.setReplyItem1List(replyItemLevel1s);
        });


        return commentListVO;
    }

    @Override
    public CommentListVO oneComment(String commentId) {
        VideoComment videoComment = videoCommentMapper.selectOne(new QueryWrapper<VideoComment>().lambda().eq(VideoComment::getId, commentId));
        CommentListVO commentListVO = new CommentListVO();
        BeanUtils.copyProperties(videoComment,commentListVO);
        // 补充用户信息
        SysUser createUser = feignSystemApi.findById(videoComment.getCreateBy());
        commentListVO.setNickname(createUser.getNickname());
        commentListVO.setAvatar(createUser.getAvatar());
        commentListVO.setIsAlreadyDisLike(isAlreadyDisLike(commentId, WebUtils.getUserId()));
        commentListVO.setIsAlreadyLike(isAlreadyLike(commentId, WebUtils.getUserId()));
        return commentListVO;
    }

    @Override
    public IPage<ReplyListOfCommentVO> replyListOfComment(ReplyListOfCommentDTO replyListOfCommentDTO) {
        Page<VideoComment> videoPageParam = new Page<>(replyListOfCommentDTO.getCurrent(), replyListOfCommentDTO.getSize());
        Page<VideoComment> videoCommentPage = (Page<VideoComment>)videoCommentMapper.selectPage(videoPageParam, new QueryWrapper<VideoComment>().lambda().eq(VideoComment::getPid, replyListOfCommentDTO.getCommentId()).orderByDesc(VideoComment::getCreateBy));
        IPage<ReplyListOfCommentVO> commentListVO = CommonBeanUtil.pageVo(videoCommentPage, ReplyListOfCommentVO.class);
        commentListVO.getRecords().forEach(item -> {

            // 补充用户信息
            SysUser createUser = feignSystemApi.findById(item.getCreateBy());
            item.setNickname(createUser.getNickname());
            item.setAvatar(createUser.getAvatar());

            // 补充是否 用户点击了 喜欢
            item.setIsAlreadyLike(isAlreadyLike(item.getId(),WebUtils.getUserId()));
            // 补充是否 用户点击了 踩
            item.setIsAlreadyDisLike(isAlreadyDisLike(item.getId(),WebUtils.getUserId()));
        });

        return commentListVO;
    }

    @Override
    public void reply(VideoReplyDTO videoReplyDTO) {

        VideoComment videoComment = new VideoComment(WebUtils.getUserId(), WebUtils.getUserId());
        BeanUtils.copyProperties(videoReplyDTO, videoComment);
        videoCommentMapper.insert(videoComment);
        if(videoReplyDTO.getPid().equals(videoReplyDTO.getVideoId())){
            videoMapper.addCommentCount(videoReplyDTO.getVideoId());
        }
        videoCommentMapper.addCommentCount(videoReplyDTO.getPid());
    }

    @Override
    public Integer like(LikeDTO likeDTO) {
        // 点赞操作
        Integer isLike = likeDTO.getIsLike();
        if(isLike != null){
            VideoCommentLikeRecord videoCommentLikeRecord = videoCommentLikeRecordMapper.selectOne(new QueryWrapper<VideoCommentLikeRecord>().lambda().eq(VideoCommentLikeRecord::getUserId, WebUtils.getUserId()).eq(VideoCommentLikeRecord::getCommentId, likeDTO.getId()).eq(VideoCommentLikeRecord::getType, 1));
            if(isLike > 0 && videoCommentLikeRecord == null){
                // 点赞操作
                videoCommentMapper.like(likeDTO.getId());
                VideoCommentLikeRecord videoLikeRecord = new VideoCommentLikeRecord(WebUtils.getUserId(), likeDTO.getId(), 1);
                videoCommentLikeRecordMapper.insert(videoLikeRecord);
            }else if(isLike < 0 && videoCommentLikeRecord != null){
                // 取消点赞操作
                videoCommentMapper.cancelLike(likeDTO.getId());
                videoCommentLikeRecordMapper.delete(new QueryWrapper<VideoCommentLikeRecord>().lambda()
                        .eq(VideoCommentLikeRecord::getUserId, WebUtils.getUserId())
                        .eq(VideoCommentLikeRecord::getCommentId, likeDTO.getId())
                        .eq(VideoCommentLikeRecord::getType,1));
            }
            VideoComment videoComment = videoCommentMapper.selectById(likeDTO.getId());
            return videoComment.getLikeCount();
        }
        // 点踩操作
        Integer isDisLike = likeDTO.getIsDisLike();
        if(isDisLike != null){
            VideoCommentLikeRecord videoCommentLikeRecord = videoCommentLikeRecordMapper.selectOne(new QueryWrapper<VideoCommentLikeRecord>().lambda().eq(VideoCommentLikeRecord::getUserId, WebUtils.getUserId()).eq(VideoCommentLikeRecord::getCommentId, likeDTO.getId()).eq(VideoCommentLikeRecord::getType, 0));
            if(isDisLike > 0 && videoCommentLikeRecord == null){
                // 点踩操作
                videoCommentMapper.disLike(likeDTO.getId());
                VideoCommentLikeRecord videoLikeRecord = new VideoCommentLikeRecord(WebUtils.getUserId(), likeDTO.getId(), 0);
                videoCommentLikeRecordMapper.insert(videoLikeRecord);

            }else if(isDisLike < 0 && videoCommentLikeRecord != null){
                // 取消点踩操作
                videoCommentMapper.cancelDisLike(likeDTO.getId());
                videoCommentLikeRecordMapper.delete(new QueryWrapper<VideoCommentLikeRecord>().lambda()
                        .eq(VideoCommentLikeRecord::getUserId, WebUtils.getUserId())
                        .eq(VideoCommentLikeRecord::getCommentId, likeDTO.getId())
                        .eq(VideoCommentLikeRecord::getType,0));
            }
            VideoComment videoComment = videoCommentMapper.selectById(likeDTO.getId());
            return videoComment.getDislikeCount();
        }
        return null;
    }

    private Boolean isAlreadyLike(String commentId, String userId ){
        VideoCommentLikeRecord videoCommentLikeRecordLike = videoCommentLikeRecordMapper.selectOne(new QueryWrapper<VideoCommentLikeRecord>().lambda()
                .eq(VideoCommentLikeRecord::getCommentId, commentId)
                .eq(VideoCommentLikeRecord::getType, 1)
                .eq(VideoCommentLikeRecord::getUserId,userId));
        return (videoCommentLikeRecordLike != null ? true : false);
    }

    private Boolean isAlreadyDisLike(String commentId, String userId ){
        VideoCommentLikeRecord videoCommentLikeRecordDisLike = videoCommentLikeRecordMapper.selectOne(new QueryWrapper<VideoCommentLikeRecord>().lambda()
                .eq(VideoCommentLikeRecord::getCommentId, commentId)
                .eq(VideoCommentLikeRecord::getType, 0)
                .eq(VideoCommentLikeRecord::getUserId, userId));
        return (videoCommentLikeRecordDisLike != null ? true : false);
    }

}
